import 'package:connectivity/connectivity.dart';
import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:flutter/widgets.dart';
import 'package:sqflite/sqflite.dart';
import 'package:ymt/api/apis.dart';
import 'package:ymt/db/offline_database_provider.dart';
import 'package:ymt/model/category.dart';
import 'package:ymt/model/product.dart';
import 'package:ymt/main.dart';
import 'package:ymt/ui/preview.dart';
import 'package:ymt/ui/filter_page.dart';
import 'package:ymt/ui/my_favorite.dart';
import 'package:ymt/ui/settings.dart';
import 'package:ymt/utils/image.dart';
import 'package:ymt/utils/request.dart';

import '../utils/nav.dart';

class MainPage extends StatefulWidget{

  final int _companyId;
  final String _companyName;
  final String _loginToken;


  const MainPage(this._companyId, this._companyName, this._loginToken);

  @override
  State<StatefulWidget> createState() {
    return _PageState(_companyId, _companyName, _loginToken);
  }
}

class _PageState extends State<MainPage>{

  Color primaryColor = Color.fromARGB(255,179,141,96);
  var _categories = <Category>[];
  Category _currentCategory;
  var _subCategories = <Category>[];
  Category _currentSubCategory;
  var _products = <Product>[];
  var _pageIndex = 1;

  final int _companyId;
  final String _companyName;
  bool isLoadComplete;

  Dio dio;

  var _currentGrade = "0";

  bool _loadOffline = false;
  Database _db;

  bool showGradeButtons = false;
  final String _loginToken;

  _PageState(this._companyId, this._companyName, this._loginToken);// 切换grade


  @override
  void initState() {
    executeTask();
    super.initState();
  }

  executeTask() async {
    var connectivityResult = await Connectivity().checkConnectivity();
    print(connectivityResult);
    if (connectivityResult == ConnectivityResult.none) {
      _loadOffline = true;
    }else{
      _loadOffline = false;
      initDio();
    }
    getCategories();
  }

  void initDio(){
    dio = Request.dio();
  }

  @override
  Widget build(BuildContext context) {
    var topBar = _buildTopBar();
    Widget categories = _buildHeightContainer(_buildCategoriesBar(), EdgeInsets.only(top: 5,left: 10,right: 10));
    Widget subCategories = _buildHeightContainer(_buildSubCategoriesBar(), EdgeInsets.only(top: 5, bottom: 20, left: 10,right: 10));
    Widget content = Expanded(child: _buildGrid(),);
    List<Widget> verticalsChildren = [topBar, categories, subCategories, content];
    List<Widget> children = List();
    Widget verticalContainer = _buildVerticalContainer(verticalsChildren);
    children.add(verticalContainer);
    if(showGradeButtons){
      var buttons = Container(child: _buildGradeSelector(),alignment: Alignment.center,color: Color(0xaf000000),);
      children.add(buttons);
    }
    return Stack(children: children,);
  }

  Widget _buildGradeSelector(){
    var circle1 = click(_buildCircleButton("品牌",Colors.amberAccent), (){
      changeGrade("20");
    });
    var circle2 = click(_buildCircleButton("精品",Colors.blue), (){
      changeGrade("10");
    });
    var circle3 = click(_buildCircleButton("爆品",Colors.deepOrangeAccent), (){
      changeGrade("0");
    });
    return Row(children: <Widget>[circle1, circle2, circle3],mainAxisAlignment: MainAxisAlignment.center,);
  }

  changeGrade(grade){
    print(grade);
    if(_currentGrade.compareTo(grade)==0){
      setState(() {
        showGradeButtons = false;
      });
      return;
    }
    setState(() {
      showGradeButtons = false;
      _products.clear();
    });
    _pageIndex = 1;
    _currentGrade = grade;
    // 请求产品数据
    getProducts({
      "company_id": _companyId,
      "catid":_currentSubCategory.id,
      "name": _currentCategory.name,
      "filter": _currentSubCategory.name,
      "grade": _currentGrade,
      "page": _pageIndex
    });
  }

  Widget _buildCircleButton(text, color) {
    var circle = Container(decoration: BoxDecoration(shape: BoxShape.circle, color: color),
      child: Text(text, style: TextStyle(fontSize: 18),),width: 70,height: 70,alignment: Alignment.center,margin: EdgeInsets.all(20),);
    return circle;
  }


  Widget _buildTopBar(){
    Text text = Text(companyAndGrade(), textAlign: TextAlign.left,);
    Align left = Align(alignment: Alignment.centerLeft, child: text,);

    var fav = rightButton("收藏", () => {Nav.nav(context, FavoritePage())});
    var filter = rightButton("筛选", () => {Nav.wrapNav(context, FilterPage(_companyId, context))});
    var grade = rightButton("切换等级", (){
        setState(() {
          showGradeButtons = !showGradeButtons;
        });
    });
    var setting = rightButton("设置", () async {
      var data = await  Nav.nav(context, MaterialApp(
        title: '易卖通',
        theme: new ThemeData.dark(),
        home: new Scaffold(
          body: SettingPage(context, _loginToken)),
        ),
      );
      if(data != null){
        if("logout".compareTo(data)==0){
          Navigator.pushAndRemoveUntil(context, new MaterialPageRoute(builder: (context) =>  LaunchPage()), (route) => route == null);
        }
        print(data);
      }
    });

    Widget right = Row(children: <Widget>[fav, filter, grade, setting], mainAxisAlignment: MainAxisAlignment.end,);

    return Container(margin: EdgeInsets.only(top: 33, left: 10),
      child: Stack(children: <Widget>[left, right],),);
  }

  String companyAndGrade(){
    if("20".compareTo(_currentGrade) == 0){
      return "$_companyName | 品牌";
    }else if("10".compareTo(_currentGrade) == 0){
      return "$_companyName | 精品";
    }else if("0".compareTo(_currentGrade) == 0){
      return "$_companyName | 爆品";
    }
  }

  rightButton(text, onTap) {
    return click(Container(child: Text(text, style: TextStyle(fontSize: 15),), margin: EdgeInsets.only(right: 30),alignment: Alignment.centerRight),onTap);
  }

  Widget click(child, onTap) {
    return GestureDetector(child: child, onTap: onTap,);
  }

  /*####################### 一级分类 ##########################*/

  Widget _buildCategoriesBar() {
    return ListView.builder(
        scrollDirection: Axis.horizontal,
        itemCount: _categories.length,
        itemBuilder: (context, position) {
          if(_categories.isNotEmpty) {
            return _buildCategoryItem(_categories[position]);
          }else{
            return Container();
          }
        });
  }

  Widget _buildCategoryItem(Category category){
    // 记住当前分类
    var textColor = Colors.white;
    if(_currentCategory != null){
      if(_currentCategory.id == category.id){
        textColor = primaryColor;
      }
    }
    var text = Text(category.name, style: TextStyle(color: textColor, fontSize: 18),);
    return GestureDetector(
      child: _buildTextContainerWithBottomLine(text, textColor, textColor != Colors.white),
      onTap: (){
        updateCurrentCategory(category);
        _pageIndex = 1;
        getSubCategories({"id": _companyId, "catid": category.id});
      },);
  }

  //更新当前目录状态（变成选中颜色）
  void updateCurrentCategory(category){
    setState(() {
      _products.clear();
      _currentCategory = category;
    });
  }

  /*####################### 二级分类 ##########################*/

  Widget _buildSubCategoriesBar() {
    return ListView.builder(
      scrollDirection: Axis.horizontal,
      itemCount: _subCategories.length,
      itemBuilder: (context, position) {
        if(_subCategories.isNotEmpty && position < _subCategories.length) {
          return _buildSubCategoryItem(_subCategories[position]);
        }else{
          return Container();
        }
      },
    );
  }

  Widget _buildSubCategoryItem(Category category) {
    var textColor = Colors.white;
    if(_currentSubCategory != null){
      if(_currentSubCategory.id == category.id){
        textColor = primaryColor;
      }
    }
    var text = Text(category.name, style: TextStyle(color: Colors.white, fontSize: 15),);
    return GestureDetector(child: _buildTextContainer(text, textColor, _currentSubCategory.id == category.id), onTap: () =>
    {
      //点击子分类获取产品列表
      _pageIndex = 1,
      updateCurrentSubCategory(category),
      getProducts({
        "company_id": _companyId,
        "name": _currentCategory.name,
        "catid":category.id,
        "filter": category.name,
        "grade": _currentGrade,
        "page": _pageIndex
      }),
    },);
  }

  void updateCurrentSubCategory(category){
    setState(() {
      _products.clear();
      _currentSubCategory = category;
    });
  }

  Widget _buildTextContainer(child, color, select) {
    BoxDecoration boxDecoration;
    if(select){
      boxDecoration = BoxDecoration(color: color, borderRadius: BorderRadius.all(Radius.circular(18)));
    }else{
      boxDecoration = BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(18)),
          border: Border.all(color: color));
    }
    return Container(padding: EdgeInsets.symmetric(vertical: 3, horizontal: 12),
      child: child,
      alignment: Alignment.center,
      margin: EdgeInsets.symmetric(vertical: 8, horizontal: 10),
      decoration: boxDecoration,);
  }

  Widget _buildTextContainerWithBottomLine(child, color, indicate) {
    UnderlineTabIndicator underlineTabIndicator;
    if(indicate){
      underlineTabIndicator = UnderlineTabIndicator(borderSide: BorderSide(width: 1, color: color));
    }
    return Container(child: Container(
      padding: EdgeInsets.symmetric(vertical: 8, horizontal: 2),
      child: child,
      decoration: underlineTabIndicator,),
      padding: EdgeInsets.symmetric(vertical: 6, horizontal: 10),
      decoration: BoxDecoration(color: ThemeData
          .dark()
          .scaffoldBackgroundColor),);
  }

  Widget _buildContainerWithBottomLine(Text child, color) {
    return Container(padding: EdgeInsets.symmetric(vertical: 4, horizontal: 15),
      child: Stack(alignment: Alignment.bottomCenter, children: <Widget>[child, Container(height: 1, color: color,)],),
      margin: EdgeInsets.symmetric(vertical: 8, horizontal: 10),);
  }

  Widget _buildHeightContainer(child, margin){
    return Container(child: child,height: 50,margin: margin,);
  }

  /*####################### 产品列表 ##########################*/

  Widget _buildGrid() {
    return new GridView.builder(
      padding: EdgeInsets.only(left: 22, right: 22,),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          mainAxisSpacing: 12,
          crossAxisSpacing: 12,
          crossAxisCount: 4,
          childAspectRatio: 16 / 9),
      itemBuilder: (context, position) {
        if (_products != null && _products.isNotEmpty) {
          if (position == _products.length) {
            //分页加载
            _pageIndex++;
            getProducts({
              "company_id": _companyId,
              "catid":_currentSubCategory.id,
              "name": _currentCategory.name,
              "filter": _currentSubCategory.name,
              "grade": _currentGrade,
              "page": _pageIndex
            });
          }
          if (position < _products.length) {
            return _buildImage(_products[position].main_picture, position);
          }
        }
        return Container();
      }, itemCount: _products.length + 1,
      physics: BouncingScrollPhysics(),
    );
  }

  Widget _buildImage(img, position){
    return GestureDetector(child: CacheImage.load(img), onTap: () =>{
      Navigator.push(context, MaterialPageRoute(builder: (context) => MaterialApp(
        title: '易卖通',
        theme: new ThemeData.dark(),
        home: new Scaffold(
          body: new Center(
            child: DetailsPage( _products, position, context),
          ),
        ),
      )))
    },);
    return CacheImage.imageClickToDetails(context, img, _products, position);
  }

  Widget _buildVerticalContainer(widgets){
    return Column(children: widgets,);
  }


  // ====================== 数据请求 ==========================

  void getCategories() async {
    if(_loadOffline){
      getCategoriesFromDB();
    }else {
      try {
        Response response = await dio.get(ApiPaths.TAG_CATEGORIES, queryParameters: {"id": _companyId});
        // 刷新大分类UI
        setState(() {
          _categories = List<Category>.from(
              response.data.map((e) => Category.fromJson(e)).toList());
        });
        if (_categories != null && _categories.isNotEmpty) {
          // 赋值当前分类数据输出第一个子分类
          _currentCategory = _categories[0];
          // 请求子分类接口
          getSubCategories({"id": _companyId, "catid": _currentCategory.id});
        } else {
          // 清空子分类和产品列表
        }
      } catch (e) {
        print(e);
      }
    }
  }

  getCategoriesFromDB(){
    OfflineDatabaseProvider().open((Database db) async {
      _db = db;
      List<Map> maps = await _db.query(OfflineDatabaseProvider.TABLE_CATEGORIES,
          where: "is_parent = ? AND company_id = ?",
          whereArgs: [1, _companyId],
          orderBy: "position");
      print(maps);
      setState(() {
        _categories = maps.map((e) => Category.fromJson(e)).toList();
      });
      if (_categories != null && _categories.isNotEmpty) {
        // 赋值当前分类数据输出第一个子分类
        _currentCategory = _categories[0];
        // 请求子分类接口
        getSubCategories({"id": _companyId, "catid": _currentCategory.id});
      } else {
        // 清空子分类和产品列表
      }
    });
  }

  void getSubCategories(params) async {
    if(_loadOffline){
      getSubCategoriesFromDB(params);
    }else {
      try {
        var response = await dio.get(ApiPaths.TAG_CATEGORIES, queryParameters: params);
        _subCategories = List<Category>.from(
            response.data.map((e) => Category.fromJson(e)).toList());
        // 赋值当前子分类未返回第一个数据，刷新当前子分类UI
        if (_subCategories != null && _subCategories.isNotEmpty) {
          _currentSubCategory = _subCategories[0];

          // 请求产品数据
          getProducts({
            "company_id": _companyId,
            "catid":_currentSubCategory.id,
            "name": _currentCategory.name,
            "filter": _currentSubCategory.name,
            "grade": _currentGrade,
            "page": _pageIndex
          });
        } else {
          //清空产品列表
        }
      } catch (e) {
        print(e);
      } finally {

      }
    }
  }

  getSubCategoriesFromDB(params) async {
    print(params);
    List<Map> maps = await _db.query(OfflineDatabaseProvider.TABLE_CATEGORIES,
        where: "parent_id = ? AND company_id = ?",
        whereArgs: [params["catid"], params["id"]],
        orderBy: "position");
    print(maps);
    setState(() {
      _subCategories = maps.map((e) => Category.fromJson(e)).toList();
    });
    if (_subCategories != null && _subCategories.isNotEmpty) {
      // 赋值当前分类数据输出第一个子分类
      _currentSubCategory = _subCategories[0];
      // 请求子分类接口
      getProducts({
        "company_id": _companyId,
        "catid":_currentSubCategory.id,
        "name": _currentCategory.name,
        "filter": _currentSubCategory.name,
        "grade": _currentGrade,
        "page": _pageIndex
      });
    } else {
      // 清空子分类和产品列表
    }
  }

  void getProducts(Map<String, dynamic> params) async {
    var page = params["page"];
    if(_loadOffline){
      getProductsFromDB(params["catid"], page);
    }else {
      try {
        isLoadComplete = false;
        params.remove("catid");
        var response = await dio.get(ApiPaths.PRODUCTS, queryParameters: params);
        List<Product> list = List<Product>.from(
            response.data.map((e) => Product.fromJson(e)).toList());
        updateProducts(list, page);
      } catch (e) {
        print(e);
      }
    }
  }

  getProductsFromDB(catId, page) async {
    List<Map> companies = await _db.query(OfflineDatabaseProvider.TABLE_COMPANIES, where: "id = ?",whereArgs: [_companyId]);
    var company = companies[0];
    int companyRate = company["rate1"];
    print("公司比率：$companyRate");
    List<Map> categories = await _db.query(OfflineDatabaseProvider.TABLE_CATEGORIES,where: "id = ? AND company_id = ?", whereArgs: [catId, _companyId]);
    var category = categories[0];
    int categoryRate = category["retail_rate"];
    print("分类比率：$categoryRate");
    List<Map> maps = await _db.rawQuery("SELECT * FROM ${OfflineDatabaseProvider.TABLE_PRODUCTS} WHERE product_category_id = ? ORDER BY position DESC LIMIT 12 OFFSET $page",[catId]);
    List<Product> list = List();
    if(maps != null){
      print(maps);
      list = maps.map((e){
        Map<String,dynamic> newMap = Map.from(e);
        if(e.containsKey("retail_rate")){
          var rate = e["retail_rate"];
          if(rate == null){
            rate = categoryRate;//分类比率
            if(rate == null){
              rate = companyRate;//公司比率
            }
            newMap["retail_rate"] = rate;
          }
        }
        return Product.fromMap(newMap);
      }).toList();
    }
    updateProducts(list, page);
  }

  void updateProducts(List<Product> list, page) {
    if(list.isNotEmpty) {
      // 返回了数据则追加数据，刷新UI
      setState(() {
        _products.addAll(list);
      });
    }else{
      // 如果第一页数据为空，并且当前有数据则清空产品列表
      if (page <= 1) {
        if(_products.isNotEmpty){
          print("请求第$page页，返回${_products.length}条数据");
          setState(() {
            _products.clear();
          });
        }
      }

    }
  }

}

